package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SettingsService {
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //查询通用设置,编写保存用户通知的业务逻辑
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        vo.setId(userId);

        //2、获取用户的手机号码
        String mobile = UserHolder.getMobile();
        vo.setPhone(mobile);

        //3、获取用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢骚嘛？" : question.getTxt();
        vo.setStrangerQuestion(txt);

        //4、获取用户的APP通知开关数据
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }

        return vo;


    }

    //设置陌生人问题
    public void saveQuestion(String content) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api查询当前用户的陌生人问题
        Question question = questionApi.findByUserId(userId);

        //3、判断问题是否存在
        if (question == null) {
            //3.1 如果不存在，保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        } else {
            //3.2 如果存在，更新
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    //通知设置
    public void saveSettings(Map map) {
        boolean likeNotification = (boolean) map.get("likeNotification");
        boolean pinglunNotification = (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (boolean) map.get("gonggaoNotification");
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询用户的通知设置
        Settings settings = settingsApi.findByUserId(userId);

        //3、判断
        if (settings == null) {
            //保存
            settings = new Settings();
            settings.setId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);

        } else {
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.update(settings);
        }

    }

    //编写查询用户黑名单列表的业务逻辑
    public PageResult blacklist(int page, int size) {
        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询用户的黑名单分页列表  Ipage对象
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId, page, size);
        //3、对象转化，将查询的Ipage对象的内容封装到PageResult中
        PageResult pr = new PageResult(page, size, iPage.getTotal(), iPage.getRecords());
        //4、返回
        return pr;
    }

    //完成移除黑名单业务逻辑编写
    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.delete(userId, blackUserId);
    }

    /**
     * 发送验证码
     */
    public void sendValidateCode() {
        // 获取手机号
        String mobile = UserHolder.getMobile();
        // 构建redis的key
        String key = Constants.SMS_CODE + mobile;
        // 查找redis中的验证码
        String codeInRedis = redisTemplate.opsForValue().get(key);
        log.info("===============Redis中的手机号:{},验证码:{}", mobile, codeInRedis);
        if (!StringUtils.isEmpty(codeInRedis)) {
            // 验证码没过期,抛出异常
            throw new BusinessException(ErrorResult.error());
        }
        // 构建验证码
        //String validateCode = RandomStringUtils.random(6);
        String validateCode = "123456";
        log.debug("=========== 发送验证码 修改手机号码:{},验证码:{}", mobile, validateCode);
        // 发送验证码,返回结果
		/*
		Map<String, String> smsResult = smsTemplate.sendValidateCode(mobile, validateCode);
		if (smsResult==null){
			// 发送失败
			throw new TanHuaException(ErrorResult.fail());
		}
		*/
        // 验证码存入redis,设置有效时间
        redisTemplate.opsForValue().set(key, validateCode, 5, TimeUnit.MINUTES);
    }

    public boolean checkVerificationCode(String verificationCode) {
        // 获取当前登录用户的手机号
        String mobile = UserHolder.getMobile();
        // 构建redisKey
        String key = Constants.SMS_CODE + mobile;
        // 获取key值
        String codeInRedis = redisTemplate.opsForValue().get(key);
        // 删除键值,避免重复提交
        redisTemplate.delete(key);
        log.info("=========== 修改手机号:{} 验证码:{},用户输入的验证码:{}", mobile, codeInRedis, verificationCode);
        if (StringUtils.isEmpty(codeInRedis)) {
            // 验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        // 输入验证码和数据库验证码比较,一样返回true,不一样返回false
        return codeInRedis.equals(verificationCode);
    }

    public void changeMobile(String phone, String token) {
        // 获取用户id
        Long userId = UserHolder.getUserId();
        // 调用api更新手机号
        userApi.updateMobile(userId, phone);
        log.info("=========== 修改手机号的用户:{},旧手机号:{},新手机号:{}", userId, UserHolder.getMobile(), phone);
        // 删除token让用户重新登录
        redisTemplate.delete(token);
    }

}
